//
// Created by 17775 on 2024/11/21.
//

#include "beam_line_view.h"
#include "ui_Beam_Line_View.h"
#include <QMouseEvent>


Beam_Line_View::Beam_Line_View(QWidget *parent) :
        QDockWidget(parent), ui(new Ui::Beam_Line_View), beamLineResult(new Beam_Line_Result(this)) {
    ui->setupUi(this);
    setWindowTitle("BeamLine");

    setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::WindowCloseButtonHint |Qt::WindowMinimizeButtonHint
                   | Qt::WindowMaximizeButtonHint);
    setAllowedAreas(Qt::NoDockWidgetArea);

    common2DView = new Common_2DView();
    // 创建菜单面板和布局
    menuPanel = new QWidget();
    menuLayout = new QVBoxLayout(menuPanel);

    // 创建一系列功能按钮
    btnSave = new QPushButton("Save Beam Line");
    btnGenerateSingle = new QPushButton("Generate Single Measurement");
    btn2DView = new QPushButton("2D View");
    btnYCrossSection = new QPushButton("Y Cross Section");
    btnLineResults = new QPushButton("Line Results");
    btnSummedIntensityPreview = new QPushButton("SummedIntensity");
    btnCenterPreview = new QPushButton("Center");
    btnWidthPreview = new QPushButton("Width");
    btnPeakIntensityPreview = new QPushButton("PeakIntensity");
    btnPeakPositionPreview = new QPushButton("PeakPosition");
    btnSelect = new QPushButton("Select");
    btnReport = new QPushButton("Report");

    // 将按钮添加进菜单布局
    menuLayout->addWidget(btnSave);
    menuLayout->addWidget(btnGenerateSingle);
    menuLayout->addWidget(btn2DView);
    menuLayout->addWidget(btnYCrossSection);
    menuLayout->addWidget(btnLineResults);
    menuLayout->addWidget(btnSummedIntensityPreview);
    menuLayout->addWidget(btnCenterPreview);
    menuLayout->addWidget(btnWidthPreview);
    menuLayout->addWidget(btnPeakIntensityPreview);
    menuLayout->addWidget(btnPeakPositionPreview);
    menuLayout->addWidget(btnSelect);
    menuLayout->addWidget(btnReport);

    //menuLayout->addStretch();

    menuPanel->setFixedWidth(200);

    // 设置图表标题、Y轴标签等（假设 charts 是 CommonChart 类型的数组）
    charts[0]->setName("Y Cross Section");
    charts[0]->setYLabel("Y Cross Section");
    charts[0]->setTitle("Y Cross Section");
    charts[1]->setName("Summed Intensity");
    charts[1]->setYLabel("Summed Intensity");
    charts[1]->setTitle("Summed Intensity");
    charts[2]->setName("Center of Gravity");
    charts[2]->setYLabel("Center of Gravity");
    charts[2]->setTitle("Center of Gravity");
    charts[3]->setName("Width 4sigma");
    charts[3]->setYLabel("Width 4sigma");
    charts[3]->setTitle("Width 4sigma");
    charts[4]->setName("Peak Intensity");
    charts[4]->setYLabel("Peak Intensity");
    charts[4]->setTitle("Peak Intensity");
    charts[5]->setName("Peak Position");
    charts[5]->setYLabel("Peak Position");
    charts[5]->setTitle("Peak Position");

    // 创建 LUT（查找表）相关控制面板
    lutPanel = new QWidget();
    lutLayout = new QVBoxLayout(lutPanel);
    cBox_Auto = new QCheckBox(); // 自动对比度复选框
    lutLayout->addWidget(cBox_Auto);
    lutPanel->setFixedWidth(80);

    // 创建主分割器用于布局不同的视图区域
    mainSplitter = new QSplitter(Qt::Vertical);
    topSplitter = new QSplitter(Qt::Horizontal);
    // 顶部水平分割器：2D视图、Y截面图、线结果面板
    topSplitter->addWidget(common2DView);
    topSplitter->addWidget(charts[0]);
    topSplitter->addWidget(beamLineResult);
    bottomSplitter = new QSplitter(Qt::Vertical);
    // 底部垂直分割器：各种分析图表
    bottomSplitter->addWidget(charts[1]);
    bottomSplitter->addWidget(charts[2]);
    bottomSplitter->addWidget(charts[3]);
    bottomSplitter->addWidget(charts[4]);
    bottomSplitter->addWidget(charts[5]);
    // 将上下分割器加入主分割器
    mainSplitter->addWidget(topSplitter);
    mainSplitter->addWidget(bottomSplitter);

    // 设置初始分割尺寸与拉伸因子
    QList<int> sizes;
    sizes << 200 << 200 << 200;
    mainSplitter->setSizes(sizes);
    mainSplitter->setStretchFactor(0, 2);
    mainSplitter->setStretchFactor(1, 2);
    mainSplitter->setStretchFactor(2, 2);

    // 创建中央部件与水平布局，组合菜单、主分割器与LUT面板
    centralWidget = new QWidget(this);
    mainLayout = new QHBoxLayout(centralWidget);
    mainLayout->addWidget(menuPanel);
    mainLayout->addWidget(mainSplitter);
    mainLayout->addWidget(lutPanel);
    centralWidget->setLayout(mainLayout);

    // 连接信号与槽函数
    connect(cBox_Auto, &QCheckBox::clicked, this, &Beam_Line_View::setAutoContrast);
    connect(btn2DView, &QPushButton::clicked, this, &Beam_Line_View::show2DView);
    connect(btnYCrossSection, &QPushButton::clicked, this, &Beam_Line_View::showYCrossView);
    connect(btnLineResults, &QPushButton::clicked, this, &Beam_Line_View::showLineResultView);
    connect(btnSummedIntensityPreview, &QPushButton::clicked, this, &Beam_Line_View::hideSummedIntensity);
    connect(btnCenterPreview, &QPushButton::clicked, this, &Beam_Line_View::hideCenter);
    connect(btnWidthPreview, &QPushButton::clicked, this, &Beam_Line_View::hideWidth);
    connect(btnPeakIntensityPreview, &QPushButton::clicked, this, &Beam_Line_View::hidePeakIntensity);
    connect(btnPeakPositionPreview, &QPushButton::clicked, this, &Beam_Line_View::hidePeakPosition);
    // 显示报告按钮，发射 reportBeamLine 信号
    connect(btnReport, &QPushButton::clicked, this, [=] () {
        emit reportBeamLine();
    });

    // 图表显示选项的信号连接
    connect(charts[0], &CommonChart::showOptions, this, [=] () {
        options[0]->show();
    });
    connect(charts[1], &CommonChart::showOptions, this, [=] () {
        options[1]->show();
    });
    connect(charts[2], &CommonChart::showOptions, this, [=] () {
        options[2]->show();
    });
    connect(charts[3], &CommonChart::showOptions, this, [=] () {
        options[3]->show();
    });
    connect(charts[4], &CommonChart::showOptions, this, [=] () {
        options[4]->show();
    });
    connect(charts[5], &CommonChart::showOptions, this, [=] () {
        options[5]->show();
    });
    // 2D视图显示选项信号连接
    connect(common2DView, &Common_2DView::showOptions, this, [=] () {
        emit showBeamLine2DView();
    });

    // 将中央部件设置为当前dock的内容
    setWidget(centralWidget);
}

// 设置窗口标题附加名称
void Beam_Line_View::setWindowTitleName(const QString& name) {
    setWindowTitle("Beam Line -" + name);
}

// 清空所有图表数据
void Beam_Line_View::clearChart() {
    charts[0]->clearChart();
    charts[1]->clearChart();
    charts[2]->clearChart();
    charts[3]->clearChart();
    charts[4]->clearChart();
    charts[5]->clearChart();
}

// 切换2D视图的显示/隐藏状态
void Beam_Line_View::show2DView() {
    if(_2DViewIsShow) {
        common2DView->hide();
        _2DViewIsShow = false;
    }
    else {
        common2DView->show();
        _2DViewIsShow = true;
    }
}

// 切换Y截面图的显示/隐藏状态
void Beam_Line_View::showYCrossView() {
    if(YCrossViewIsShow) {
        charts[0]->hide();
        YCrossViewIsShow = false;
    }
    else {
        charts[0]->show();
        YCrossViewIsShow = true;
    }
}

// 切换线结果面板的显示/隐藏状态
void Beam_Line_View::showLineResultView() {
    if(LineResultIsShow) {
        beamLineResult->hide();
        LineResultIsShow = false;
    }
    else {
        beamLineResult->show();
        LineResultIsShow = true;
    }
}

// 切换“合计强度”图表的显示/隐藏
void Beam_Line_View::hideSummedIntensity() {
    if(summedIntensityIsHide) {
        charts[1]->show();
        summedIntensityIsHide = false;
    }
    else {
        charts[1]->hide();
        summedIntensityIsHide = true;
    }
}

// 切换“中心”图表的显示/隐藏
void Beam_Line_View::hideCenter() {
    if(centerIsHide) {
        charts[2]->show();
        centerIsHide = false;
    }
    else {
        charts[2]->hide();
        centerIsHide = true;
    }
}

// 切换“宽度”图表的显示/隐藏
void Beam_Line_View::hideWidth() {
    if(widthIsHide) {
        charts[3]->show();
        widthIsHide = false;
    }
    else {
        charts[3]->hide();
        widthIsHide = true;
    }
}

// 切换“峰值强度”图表的显示/隐藏
void Beam_Line_View::hidePeakIntensity() {
    if(peakIntensityIsHide) {
        charts[4]->show();
        peakIntensityIsHide = false;
    }
    else {
        charts[4]->hide();
        peakIntensityIsHide = true;
    }
}

// 切换“峰值位置”图表的显示/隐藏
void Beam_Line_View::hidePeakPosition() {
    if(peakPositionIsHide) {
        charts[5]->show();
        peakPositionIsHide = false;
    }
    else {
        charts[5]->hide();
        peakPositionIsHide = true;
    }
}

// 设置自动对比度复选框状态
void Beam_Line_View::setAuto(bool bAuto) {
    cBox_Auto->setChecked(bAuto);
}

// 发射自动对比度信号
void Beam_Line_View::setAutoContrast() {
    auto isAuto = cBox_Auto->isChecked();
    emit sendAutoContrast(isAuto);
}

// 刷新所有图表数据
void Beam_Line_View::refreshChart() {
    charts[0]->freshChart();
    charts[1]->freshChart();
    charts[2]->freshChart();
    charts[3]->freshChart();
    charts[4]->freshChart();
    charts[5]->freshChart();
}


void Beam_Line_View::updateResult(BeamLineResult result) {
    beamLineResult->updateResult(result.dCount, result.dPositionY, result.dPositionResidualY, result.dLineTilt, result.dLineCurvature, result.dWidth,
                                 result.dPositionUncertaintyY, result.dPositionResidualUncertaintyY, result.dLineTiltUncertainty, result.dLineCurvatureUncertainty, result.dWidthUncertainty,
                                 result.dLineLength, result.dHomogeneity);
}

// 窗口关闭事件处理：询问是否保存、停止线程等
void Beam_Line_View::closeEvent(QCloseEvent *event) {
//    event->accept(); // 直接接受关闭（原被注释）
    const QMessageBox::StandardButton resBtn = QMessageBox::question(this, "RayCi", "是否保存对RayCi的更改？",
                                                                     QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
    if (resBtn == QMessageBox::Yes) {
        // 用户选择 Yes，可在此处添加保存逻辑
    } else if (resBtn == QMessageBox::No) {
        emit stopBeamLineThread(); // 停止相关线程
    } else if (resBtn == QMessageBox::Cancel) {
        event->ignore(); // 取消关闭
    }
}

// 析构函数，释放UI资源
Beam_Line_View::~Beam_Line_View() {
    delete ui;
}

void Beam_Line_View::mousePressEvent(QMouseEvent *event) {
    QDockWidget::mousePressEvent(event);
    this->raise();
    this->activateWindow();
    emit BeamLineClicked();
}